package cn.may.utils;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.UUID;

/**
 * @author May
 * @date 2020/12/03 17:31
 */
public class DownloadUtil {

    public static String download(HttpServletResponse response, String filePath) throws Exception {

        File file = new File(filePath);
        if (!file.exists()) {
            return "文件不存在";
        }
        //设置响应头
        response.setContentType("application/octet-stream");
        //设置头，通知浏览器下载的文件名
        String fileName = filePath.substring(filePath.lastIndexOf("/") + 1);
        fileName = URLEncoder.encode(fileName, "UTF-8");
        response.setHeader("content-disposition", "attachment;filename=" + fileName);
        //开始IO
        try (BufferedInputStream in = new BufferedInputStream(new FileInputStream(file))) {
            byte[] bs = new byte[1024 * 4];
            int len;
            OutputStream out = response.getOutputStream();
            while ((len = in.read(bs)) != -1) {
                out.write(bs, 0, len);
            }
            out.flush();
            out.close();
            return "success";
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
    }
}
